#include "config.h"
#include "base.h"

int main()
{
  Config::Input();
  string outfilename = "export2mysql.sql";
  string inputfilename = Config::m_output_database_dir + "new_attribute.dat";
  ifstream infile ( inputfilename.c_str() );
  ofstream outfile ( outfilename.c_str() );

  int oldindex = -1;
  int index;

  outfile<<"DROP DATABASE IF EXISTS phase1;"<<endl;
  outfile<<"CREATE DATABASE phase1;"<<endl;
  outfile<<"USE phase1;"<<endl;
  outfile<<"CREATE TABLE sample ("<<endl;
  outfile<<"  id      INT,"<<endl;
  outfile<<"  enc_data MEDIUMBLOB,"<<endl;
  outfile<<"  PRIMARY KEY (id)\n);"<<endl;
  
  while(1)
	{
	  try
		{
		  size_t len;
		  infile.read((char *)&len, sizeof(len));
		  char * strtmp = new char[len];
		  infile.read(strtmp, len);
		  delete [] strtmp;

		  infile.read((char *)&len, sizeof(len));
		  strtmp = new char[len];
		  infile.read(strtmp, len);
		  delete [] strtmp;

		  infile.read((char *)&index, sizeof(unsigned long));
		  if (oldindex != index)
			{
			  stringstream ss;
			  ss<<Config::m_output_database_dir<<index/5000<<"/"<<index%5000<<"_1";
		  
			  outfile<<"INSERT INTO sample (id, enc_data) VALUES ("<<endl;
			  outfile<<"                                          "<<index<<", ";
			  outfile<<"                                          ";
			  outfile<<"LOAD_FILE('"<<ss.str()<<"')"<<endl<<")"<<endl;
			  oldindex = index;
			}
		}
	  catch (ifstream::failure e)
		{
		  cout<<"further reading failed "<<endl;
		  break;
		}
	}
}
